﻿<%@ WebHandler Language="C#" Class="TestHandler" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using Dln.Common.Helper;
using Dln.Common;
using Dln.Model;
using Dln.Handler;
using log4net;

public class TestHandler : HandlerBase
{
    //Test
    public void Test()
    {
        string empID = HttpContext.Current.Request.Form["EMPID"];  //工号
        int type = Convert.ToInt32(HttpContext.Current.Request.Form["Type"]); //任务状态
        StringBuilder sql = new StringBuilder();
        sql.Append(@" SELECT  ROW_NUMBER() OVER ( ORDER BY main.rowno DESC ) sRowNo ,
        k.HospID tHospID ,
        HospName + ( CASE WHEN main.taskselect = '1' THEN '----进行中'
                          WHEN main.cstaskselect = '1' THEN '----进行中'
                          WHEN main.taskselect = '2' THEN '----已暂停'
                          ELSE ''
                     END ) tHospName ,
        main.rowno trowno ,
        ( ( CASE WHEN main.gztnr IS NULL THEN ''
                 ELSE main.gztnr
            END ) + ( CASE WHEN main.cdnr IS NULL THEN ''
                           ELSE main.cdnr
                      END ) + ( CASE WHEN main.gnnr IS NULL THEN ''
                                     ELSE main.gnnr
                                END ) + main.InForMation ) tInForMation ,
        Main.RcvDate tRcvDate ,
        main.Note tNote ,
        a.EmpName kfempname ,
        CASE BMType
          WHEN 0 THEN '开发'
          WHEN 1 THEN '项目'
          WHEN 2 THEN '测试'
          WHEN 3 THEN '行政'
          WHEN 4 THEN '商务'
          WHEN 5 THEN '客服'
        END AS tbmtype ,
        CASE type
          WHEN 0 THEN '报表bug'
          WHEN 4 THEN '新增功能'
          WHEN 5 THEN '新接口'
          WHEN 8 THEN '程序bug'
          WHEN 9 THEN '程序修改'
          WHEN 1 THEN '新增报表'
          WHEN 2 THEN '报表修改'
          WHEN 3 THEN '数据核对'
          WHEN 6 THEN '修正对方错误'
          WHEN 11 THEN '现场技术服务'
          WHEN 10 THEN '测试'
          WHEN 12 THEN '行政管理'
          WHEN 7 THEN '远程技术支持'
          END AS tType
FROM    {0} k
        LEFT JOIN hosp ON k.HospID = hosp.hospid
        LEFT JOIN Emp a ON k.empid = a.EmpID
        LEFT JOIN main ON k.HospID = main.hospid
                          AND k.rowno = main.rowno ");

        sql.AppendFormat(@" WHERE 1 = 1  AND k.empid = '{0}'  AND a.EMPNAME IS NOT NULL ", empID);

        DataTable dts = SqlHelper.GetDataTable(string.Format("SELECT ORGID FROM dbo.BHD03030 with(nolock) WHERE EMPID = '{0}'", empID));
        if (dts != null && dts.Rows.Count > 0)
        {
            //开发
            if (dts.Rows[0]["ORGID"].ToString().Substring(0, 4) == "0303")
            {
                sql = new StringBuilder(string.Format(sql.ToString(), "kfff"));
                //已完成
                if (type == 1)
                {
                    sql.AppendFormat(@" k.kfwcsj>=dateadd(month,-1,getdate())");
                }
                else if (type == 2)   //未完成
                {
                    sql.AppendFormat(@"  AND ( k.kffgflag = 'ok'
                                          OR k.kfwcsj = '1900-01-01 00:00:00.000 '
                                        )
                                    AND ( main.ztcolor <> '12'
                                          OR main.ztcolor IS NULL
                                        )");
                }
            }
            else if (dts.Rows[0]["ORGID"].ToString().Substring(0, 4) == "0304")   //测试
            {
                sql = new StringBuilder(string.Format(sql.ToString(), "csff"));

                //已完成
                if (type == 1)
                {
                    sql.AppendFormat(@" AND k.cswcsj>=dateadd(MONTH,-2,getdate()) ");
                }
                else if (type == 2)    //未完成
                {
                    sql.AppendFormat(@"AND ( k.cswcsj IS  NULL
                                              OR k.cswcsj = '1900-01-01 00:00:00.000 '
                                            )
                                        AND ( main.ztcolor <> '12'
                                              OR main.ztcolor IS NULL
                                            )");
                }
            }
        }
        sql.AppendFormat(" ORDER BY main.rowno desc");

        DataTable dt = SqlHelper.GetDataTable(sql.ToString());
        HttpContext.Current.Response.Write(SqlHelper.GetTablejson(dt));
        HttpContext.Current.Response.End();
    }

    //login
    public void SetPwd()
    {
        string patientName = _httpRequestForm["PatientName"].ToString();
        string idNum = _httpRequestForm["IdNum"].ToString();
        string md5IdNum = SecurityHelper.Md5EncryptStr32(idNum);
        string sql = string.Format("SELECT EMPID FROM dbo.BHD03030 WITH(NOLOCK) WHERE EMPID = '{0}' and EMPPASSWORD='{1}'", patientName, md5IdNum);
        DataTable dt = SqlHelper.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            setLoginCookie(patientName);
            PrintSuccessJson(String.Format("page/MyTest1.aspx?idNum={0}", patientName));
        }
        PrintErrorJson("输入的用户名或密码有误");

    }

    //login
    public void GetOrderInfo()
    {
        int OrderId = Convert.ToInt32(_httpReuqestString["OrderId"]);
        string cardId = _httpReuqestString["cardId"];

        //int state = Convert.ToInt32(_httpReuqestString["State"]);

        var uptModel = SqlHelper.ContextDlnOnline.From<dt_order>().Where(d => d.id == OrderId).First();
        if (uptModel != null)
        {
            if (uptModel.state == 0) //待处理
            {
                uptModel.state = 1;
                uptModel.update_name = cardId;
                uptModel.update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var count = SqlHelper.ContextDlnOnline.Update<dt_order>(uptModel);
                if (count > 0)
                {
                    PrintSuccessJson("保存成功！");
                }
                else
                {
                    PrintErrorJson("保存失败！");
                }
            }
            if (uptModel.state == 1 && uptModel.update_name == cardId) //已接受&&处理的人==当前登录人------改为已处理完成
            {
                uptModel.state = 4;
                uptModel.update_name = cardId;
                uptModel.updateComplete_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var count = SqlHelper.ContextDlnOnline.Update<dt_order>(uptModel);
                if (count > 0)
                {
                    var weChatUsersList =
                    SqlHelper.Context.From<WeChatUsers>().Where(d => d.CardID == uptModel.number).ToFirst();
                    if (weChatUsersList != null)
                    {
                        MessageHelper.ProblemNotice(weChatUsersList.Openid,
                                                               "该工单已处理完成,请及时关闭工单",
                                                             uptModel.add_time,
                                                              "问题报修",
                                                              "标题：" + uptModel.title,
                                                               "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + uptModel.id + "&cardId=" + weChatUsersList.CardID
                                                           );
                    }

                    PrintSuccessJson("保存成功！");
                }
                else
                {
                    PrintErrorJson("保存失败！");
                }
            }
            if (uptModel.state == 1 && uptModel.update_name != cardId)//已接受&&处理人!=当前登录人
            {
                PrintErrorJson("该工单已有人处理！");
            }
            if (uptModel.state == 4 && uptModel.number == cardId)//维修人已处理完成 && 发起人==登录人
            {
                int star = Convert.ToInt32(_httpReuqestString["star"]);
                uptModel.state = 3;
                uptModel.starNum = star;
                uptModel.pingJia_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                var count = SqlHelper.ContextDlnOnline.Update<dt_order>(uptModel);
                if (count > 0)
                {
                    PrintSuccessJson("保存成功！");
                }
                else
                {
                    PrintErrorJson("保存失败！");
                }
            }
            if (uptModel.state == 4 && uptModel.number != cardId) //维修人已处理完成 && 发起人!=登录人
            {
                PrintErrorJson("您没有该操作权限！");
            }
            if (uptModel.state == 3)
            {
                PrintErrorJson("该工单已处理完成！");
            }
            if (uptModel.state == 2)
            {
                PrintErrorJson("该工单已被驳回！");
            }

        }
        PrintErrorJson("未找到该报修信息！");
        //int OrderId = Convert.ToInt32(_httpReuqestString["OrderId"]);
        //string cardId = _httpReuqestString["cardId"];
        //int state = Convert.ToInt32(_httpReuqestString["State"]);
        //var uptModel = SqlHelper.ContextDlnOnline.From<dt_order>().Where(d => d.id == OrderId && d.state == 0).First();
        //if (uptModel != null)
        //{
        //    uptModel.state = 1;
        //    uptModel.update_name = cardId;
        //    uptModel.update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        //    var count = SqlHelper.ContextDlnOnline.Update<dt_order>(uptModel);
        //    if (count > 0)
        //    {
        //        PrintSuccessJson("保存成功！");
        //    }
        //    else
        //    {
        //        PrintErrorJson("保存失败！");
        //    }
        //}
        //PrintErrorJson("未找到该报修信息或该问题已有人处理");

    }

    /// <summary>
    /// 问题类型推送
    /// </summary>
    public void ProblemInfo()
    {
        ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        int OrderId = Convert.ToInt32(_httpReuqestString["OrderId"]);
        var flag = false;
        var dt_type_list = SqlHelper.ContextDlnOnline.From<dt_order>().Where(d => d.id == OrderId).First();
        if (dt_type_list != null)
        {
            if (!string.IsNullOrEmpty(dt_type_list.AppointUser))
            {
                var selfUser = SqlHelper.Context.From<WeChatUsers>().Where(d => d.CardID == dt_type_list.AppointUser).ToFirst();
                if (selfUser != null)
                {
                    MessageHelper.ProblemNotice(selfUser.Openid,
                                       "问题报修",
                                     dt_type_list.add_time,
                                      "问题报修",
                                      "标题：" + dt_type_list.title,
                                       "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + dt_type_list.id + "&cardId=" + selfUser.CardID
                                   );
                    return;
                }
            }

            var weChatUsersList = SqlHelper.Context.FromSql(string.Format("select * from WeChatUsers where charindex(',{0},',',' + Category + ',')>0 ", dt_type_list.type)).ToList<WeChatUsers>();

            if (weChatUsersList != null && weChatUsersList.Count > 0)
            {
                foreach (var childItem in weChatUsersList)
                {
                    if (string.IsNullOrEmpty(childItem.CardID))
                    {
                        PrintErrorJson("未维护工号，请联系信息科");
                    }
                    else
                    {
                        Log.InfoFormat(childItem.Openid);
                        MessageHelper.ProblemNotice(childItem.Openid,
                                        "问题报修",
                                      dt_type_list.add_time,
                                       "问题报修",
                                       "标题：" + dt_type_list.title,
                                        "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + dt_type_list.id + "&cardId=" + childItem.CardID
                                    );
                    }
                }
            }
        }
        else
        {
            PrintErrorJson("未找到该报修信息");
        }
    }

    /// <summary>
    /// 工单驳回
    /// </summary>
    public void ProblemBoHui()
    {
        int orderId = Convert.ToInt32(_httpRequestForm["OrderId"]);
        string cardId = _httpRequestForm["cardId"];
        string mark = _httpRequestForm["mark"];

        var dtTypeList = SqlHelper.ContextDlnOnline.From<dt_order>().Where(d => d.id == orderId).First();
        if (dtTypeList != null)
        {
            if (dtTypeList.state == 1 && dtTypeList.update_name != cardId || dtTypeList.state == 4 && dtTypeList.update_name != cardId)
            {
                PrintErrorJson("该工单已有人处理！");
            }

            dtTypeList.state = 2;
            dtTypeList.update_name = cardId;
            dtTypeList.update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            dtTypeList.mark = mark;
            var count = SqlHelper.ContextDlnOnline.Update<dt_order>(dtTypeList);
            if (count > 0)
            {
                var selfUser =
                        SqlHelper.Context.From<WeChatUsers>().Where(d => d.CardID == dtTypeList.number).ToFirst();
                if (selfUser != null)
                {
                    MessageHelper.ProblemNotice(selfUser.Openid,
                        "问题报修",
                        dtTypeList.add_time,
                        "工单被驳回",
                        "标题：" + dtTypeList.title,
                        "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + dtTypeList.id + "&cardId=" +
                        selfUser.CardID
                        );
                    PrintSuccessJson("驳回成功！");
                }
            }
            else
            {
                PrintErrorJson("驳回失败！");
            }
        }
        PrintErrorJson("未找到该报修信息！");
    }


    /// <summary>
    /// 类别更改
    /// </summary>
    public void ProblemTypeAlert()
    {
        int orderId = Convert.ToInt32(_httpRequestForm["OrderId"]);
        string typeId = _httpRequestForm["typeId"];
        var groupId =
            SqlHelper.ContextDlnOnline.From<dt_type_list>().Where(d => d.id == Convert.ToInt32(typeId)).First();
        var dtTypeList = SqlHelper.ContextDlnOnline.From<dt_order>().Where(d => d.id == orderId).First();
        if (dtTypeList != null)
        {
            //if (dtTypeList.state == 1 && dtTypeList.update_name != cardId || dtTypeList.state == 4 && dtTypeList.update_name != cardId)
            //{
            //    PrintErrorJson("该工单已有人处理！");
            //}

            dtTypeList.type = typeId;
            dtTypeList.state = 0;
            dtTypeList.update_name = "";
            dtTypeList.update_time = "";

            if (groupId != null)
            {
                dtTypeList.group_id = groupId.typeID.ToString();
            }
            var count = SqlHelper.ContextDlnOnline.Update<dt_order>(dtTypeList);
            if (count > 0)
            {
                if (!string.IsNullOrEmpty(dtTypeList.AppointUser))
                {
                    var selfUser =
                        SqlHelper.Context.From<WeChatUsers>().Where(d => d.CardID == dtTypeList.AppointUser).ToFirst();
                    if (selfUser != null)
                    {
                        MessageHelper.ProblemNotice(selfUser.Openid,
                            "问题报修",
                            dtTypeList.add_time,
                            "问题报修类别修改",
                            "标题：" + dtTypeList.title,
                            "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + dtTypeList.id + "&cardId=" +
                            selfUser.CardID
                            );
                    }
                    PrintSuccessJson("类别更改成功！");
                }

                var weChatUsersList =
                    SqlHelper.Context.FromSql(
                        string.Format("select * from WeChatUsers where charindex(',{0},',',' + Category + ',')>0 ",
                            dtTypeList.type)).ToList<WeChatUsers>();

                if (weChatUsersList != null && weChatUsersList.Count > 0)
                {
                    foreach (var childItem in weChatUsersList)
                    {
                        if (!string.IsNullOrEmpty(childItem.CardID))
                        {
                            MessageHelper.ProblemNotice(childItem.Openid,
                                "问题报修",
                                dtTypeList.add_time,
                                "问题报修类别修改",
                                "标题：" + dtTypeList.title,
                                "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + dtTypeList.id +
                                "&cardId=" + childItem.CardID
                                );
                            PrintSuccessJson("类别更改成功！");
                        }
                    }
                }
                else
                {
                    PrintErrorJson("类别更改失败！");
                }
            }
            PrintErrorJson("未找到该报修信息！");
        }
    }

    /// <summary>
    /// 延迟处理
    /// </summary>
    public void ProblemYanChi()
    {
        int orderId = Convert.ToInt32(_httpRequestForm["OrderId"]);
        string yctime = _httpRequestForm["yctime"];
        string mark = _httpRequestForm["mark"];

        var dtTypeList = SqlHelper.ContextDlnOnline.From<dt_order>().Where(d => d.id == orderId).First();
        if (dtTypeList != null)
        {
            dtTypeList.mark = mark;
            dtTypeList.solve_time = yctime;
            var count = SqlHelper.ContextDlnOnline.Update<dt_order>(dtTypeList);
            if (count > 0)
            {
                var selfUser =
                    SqlHelper.Context.From<WeChatUsers>().Where(d => d.CardID == dtTypeList.number).ToFirst();
                if (selfUser != null)
                {
                    MessageHelper.ProblemNotice(selfUser.Openid,
                        "问题报修",
                        dtTypeList.add_time,
                        "工单被延迟处理",
                        "标题：" + dtTypeList.title,
                        "http://www.healthyperson.cn/Page/AutoRun/SendProblem.aspx?Id=" + dtTypeList.id + "&cardId=" +
                        selfUser.CardID
                        );
                }
                PrintSuccessJson("延迟处理成功！");
            }
            PrintErrorJson("保存失败，请联系信息科");
        }
        PrintErrorJson("未找到该报修信息！");
    }

}